package com.weetop.cfw.mine.fragment

import android.content.Intent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ToastUtils
import com.kongzue.dialog.v3.MessageDialog
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.weetop.cfw.R
import com.weetop.cfw.application.CFWApplication
import com.weetop.cfw.base.presenter.imp.LeaseSaleInformationPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.ui.fragment.CommonBaseFragment
import com.weetop.cfw.base.view.LeaseSaleInformationView
import com.weetop.cfw.bean.ErrorBean
import com.weetop.cfw.bean.MyLeaseSaleInformationListBean
import com.weetop.cfw.callback.RxJavaCallBack
import com.weetop.cfw.home_page.activity.AdPayToTopActivity
import com.weetop.cfw.home_page.activity.PlantSalePublishActivity
import com.weetop.cfw.home_page.activity.PublishActivity
import com.weetop.cfw.kind.activity.WorkshopDetailActivity
import com.weetop.cfw.mine.adapter.AllLeaseSaleInformationAdapter
import com.weetop.cfw.utils.MMKVUtils
import com.weetop.cfw.utils.RetrofitUtils
import com.weetop.cfw.utils.RxJavaUtils
import kotlinx.android.synthetic.main.fragment_lease_sale_information.*


/**
 * 全部出租出售信息界面
 */
class AllLeaseSaleInformationFragment : CommonBaseFragment(), LeaseSaleInformationView,
    OnRefreshLoadMoreListener {

    private lateinit var leaseSaleInformationPresenterImp: LeaseSaleInformationPresenterImp

    private lateinit var allLeaseSaleInformationAdapter: AllLeaseSaleInformationAdapter

    private var myLeaseSaleInformationDataList: ArrayList<MyLeaseSaleInformationListBean.DataBean> =
        ArrayList()

    private var currentPageNumber = 1//当前数据的页数
    private var pageSize = 10//每页多少条数据
    private var totalCount = 0//数据总条数

    private var isRefresh = false//是否正在刷新
    private var isLoadMore = false//是否正在加载更多

    override fun getLayoutId() = R.layout.fragment_lease_sale_information

    override fun initView() {
        leaseSaleInformationPresenterImp = LeaseSaleInformationPresenterImp()
        leaseSaleInformationPresenterImp.attachView(this)
        smartRefreshLayout.setOnRefreshLoadMoreListener(this)
        smartRefreshLayout.setEnableAutoLoadMore(false)
    }

    override fun initData() {
        allLeaseSaleInformationAdapter =
            AllLeaseSaleInformationAdapter(myLeaseSaleInformationDataList)
        allLeaseSaleInformationAdapter.setContext(this@AllLeaseSaleInformationFragment)

        allLeaseSaleInformationAdapter.emptyView = emptyView
        allLeaseSaleInformationAdapter.setOnItemChildClickListener { adapter, view, position ->
            courseListItemClick(view, position)
        }
        allLeaseSaleInformationAdapter.setOnItemClickListener { adapter, view, position ->
            if (myLeaseSaleInformationDataList[position].statusX == 0) {
                WorkshopDetailActivity.startWorkshopDetailActivity(
                    context!!,
                    myLeaseSaleInformationDataList[position].infoid,
                    2
                )
            } else {
                ToastUtils.showShort("等待审核通过后查看")
            }

        }


        leaseSaleInformationRV.adapter = allLeaseSaleInformationAdapter
        leaseSaleInformationPresenterImp.getMyLeaseSaleInformationDataList(
            this,
            -1,
            currentPageNumber,
            pageSize
        )
    }

    /**
     * 订单列表item中的按钮被点击
     */
    private fun courseListItemClick(view: View, position: Int) {
        when (view.id) {
            R.id.llTop -> {
                var intent = Intent(context, AdPayToTopActivity::class.java)
                intent.putExtra("infoId", myLeaseSaleInformationDataList[position].infoid)
                startActivity(intent)
            }
            R.id.llRefresh -> {
                if (CFWApplication.vipLevel == "0") {
                    MessageDialog.show(
                        this as AppCompatActivity,
                        "提示",
                        "购买置顶广告之后才能操作",
                        "立即购买",
                        "取消"
                    )
                        .setOnOkButtonClickListener { baseDialog, v ->
                            var intent = Intent(context, AdPayToTopActivity::class.java)
                            intent.putExtra(
                                "infoId",
                                myLeaseSaleInformationDataList[position].infoid
                            )
                            startActivity(intent)
                            false
                        }
                } else {
                    isRefreshAdInfo(myLeaseSaleInformationDataList[position].infoid)
                }
            }

            R.id.llMotify -> {

                if (CFWApplication.vipLevel == "0") {
                    MessageDialog.show(
                        context as AppCompatActivity,
                        "提示",
                        "购买置顶广告之后才能操作",
                        "立即购买",
                        "取消"
                    )
                        .setOnOkButtonClickListener { baseDialog, v ->
                            var intent = Intent(context, AdPayToTopActivity::class.java)
                            intent.putExtra(
                                "infoId",
                                myLeaseSaleInformationDataList[position].infoid
                            )
                            startActivity(intent)
                            false
                        }
                } else {
                    if (myLeaseSaleInformationDataList[position].intid == 1) {
                        var intent = Intent(context, PublishActivity::class.java)
                        intent.putExtra("isMotify", true)
                        intent.putExtra(
                            "motifyInfoId",
                            myLeaseSaleInformationDataList[position].infoid
                        )
                        startActivity(intent)
                    } else {
                        var intent = Intent(context, PlantSalePublishActivity::class.java)
                        intent.putExtra("isMotify", true)
                        intent.putExtra(
                            "motifyInfoId",
                            myLeaseSaleInformationDataList[position].infoid
                        )
                        startActivity(intent)
                    }
                }
            }
            R.id.llDelete -> {
                MessageDialog.show(context as CommonBaseActivity, "提示", "是否删除该条信息？", "确定", "取消")
                    .setOnOkButtonClickListener { baseDialog, v ->
                        deleteInfo(myLeaseSaleInformationDataList[position].infoid)
                        false
                    }
            }

        }
    }

    private fun isRefreshAdInfo(infoid: Int) {
        RxJavaUtils.useInSupportFragmentOnDestoryView(
            RetrofitUtils.getApi().refreshInfo(
                MMKVUtils.getToken(),
                infoid
            ), this, object :
                RxJavaCallBack<ErrorBean>() {
                override fun onSuccess(t: ErrorBean?) {
                    isRefresh = true
                    leaseSaleInformationPresenterImp.getMyLeaseSaleInformationDataList(this@AllLeaseSaleInformationFragment, -1, 1, pageSize)
                    ToastUtils.showShort("刷新成功")
                }

                override fun onErrorResponse(throwable: Throwable?) {
                    super.onErrorResponse(throwable)
                }

                override fun onRequestError(t: ErrorBean?) {
                    super.onRequestError(t)
                }
            })
    }

    private fun deleteInfo(infoid: Int) {
        RxJavaUtils.useInSupportFragmentOnDestoryView(
            RetrofitUtils.getApi().deleteInfo(
                MMKVUtils.getToken(),
                infoid
            ), this, object :
                RxJavaCallBack<ErrorBean>() {
                override fun onSuccess(t: ErrorBean?) {
                    smartRefreshLayout.autoRefresh()
                }

                override fun onErrorResponse(throwable: Throwable?) {
                    super.onErrorResponse(throwable)
                }

                override fun onRequestError(t: ErrorBean?) {
                    super.onRequestError(t)
                }

            })
    }

    override fun getMyLeaseSaleInformationSuccess(leaseSaleInformationListBean: MyLeaseSaleInformationListBean?) {
        if (leaseSaleInformationListBean != null) {

            totalCount = leaseSaleInformationListBean.records

            isFirstLoadData = false
            if (isRefresh) {//处于刷新状态
                myLeaseSaleInformationDataList.clear()
                myLeaseSaleInformationDataList.addAll(leaseSaleInformationListBean.data)
                allLeaseSaleInformationAdapter.notifyDataSetChanged()
                isRefresh = false
                smartRefreshLayout.finishRefresh(true)
                if (leaseSaleInformationListBean.data.size > 0) {
                    currentPageNumber = 1//将当前数据页数重置为1
                }
                return
            }
            if (isLoadMore) {
                myLeaseSaleInformationDataList.addAll(leaseSaleInformationListBean.data)
                allLeaseSaleInformationAdapter.notifyDataSetChanged()
                isLoadMore = false
                smartRefreshLayout.finishLoadMore(true)
                if (leaseSaleInformationListBean.data.size > 0) {
                    currentPageNumber += 1//将当前数据页数增加1
                }
                return
            }
            myLeaseSaleInformationDataList.addAll(leaseSaleInformationListBean.data)
            allLeaseSaleInformationAdapter.notifyDataSetChanged()
        }
    }

    override fun getMyLeaseSaleInformationFailed() {
        smartRefreshLayout.finishRefresh(false)
        smartRefreshLayout.finishLoadMore(false)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (totalCount <= myLeaseSaleInformationDataList.size) {
            showNativeShortToast("暂无更多数据")
            smartRefreshLayout.finishLoadMoreWithNoMoreData()
        } else {
            isLoadMore = true
            leaseSaleInformationPresenterImp.getMyLeaseSaleInformationDataList(
                this,
                -1,
                currentPageNumber + 1,
                pageSize
            )
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        isRefresh = true
        leaseSaleInformationPresenterImp.getMyLeaseSaleInformationDataList(this, -1, 1, pageSize)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        leaseSaleInformationPresenterImp.detachView()
    }
}